#include<iostream>
using namespace std;
 #include <sys/types.h>
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include<string>
 #include <sys/wait.h>
/*错误码*/
int g_exitStatus=5;
int main()
{
   
    // pid_t pid=getpid();
    // pid_t ppid=getppid();
    // /*进程号*/
    // cout<<"pid:"<<pid<<" ppid:"<<ppid<<endl;
    // int cnt=60;
    // while(cnt--)
    // {
    //     sleep(1);
        
    // }
   
    int val=100;
    /*父进程和子进程是相互独立的，在父进程处理val，子进程不会变*/


    pid_t pid=fork();
    if(pid==-1)
    {
        perror("fork error:");
        exit(-1);
    }
    /*函数在父进程返回值就是子进程id号*/
    else if(pid==0)
    {
        sleep(3);
        cout<<"child process"<<endl;
        cout<<"child process id:"<<getpid()<<endl;
        cout<<"child process parent id:"<<getppid()<<endl;
        /*退出进程*/
   
        _exit(g_exitStatus);


        cout<<"child process val: "<<val<<endl;
        /*如何拿到父进程val?*/
        /*父进程写*/
        /*子进程读*/
        const char *filename="./text.txt";
        int fd=open(filename,O_RDONLY);
        read(fd,&val,sizeof(int));
        cout<<"child process val:"<<val<<endl;
        close(fd);                                                                                                                                                                            

    }
    else
    {
        int childStatus=0;
        /*下面两种方式是等价的*/
        
        //wait(&childStatus);
        waitpid(pid,childStatus,0);

        /*宏接受状态参数*/
        cout<<"childStatus:"<<WEXITSTATUS(childStatus)<<endl;
        /*阻塞block*/


        cout<<"parent process ret pid:"<<pid<<endl;
        cout<<"parent process"<<endl;
        cout<<"parent process id:"<<getpid()<<endl;

        cout<<"parent process val: "<<val<<endl;
        val+= 10000;
        cout<<"parent process val: "<<val<<endl;
        /*父进程写数据*/
        const char *filename="./text.txt";
        int fd=open(filename,O_RDWR| O_CREAT,0644);
        if(fd==-1)
        {
            perror("open error:");
            exit(-1);
        }
        int writeBytes= write(fd,(const void*)&val,sizeof(val));
        close(fd);
        
    }
    /*子进程父进程都打印一遍*/
    cout<<"hello world"<<endl;
    
    int cnt=100;
    while(cnt--)
    {
        sleep(1);
    }


    return 0;
}